﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using AUV5.Common;

namespace AUV5.Web.Pages
{
    public partial class ShoppingDetail : PageBaseFrontend
    {
        public IList<IOrderMessage> messagelist = new List<IOrderMessage>();
        public string lastIsRequest = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (base.IsVerified)
                {
                    if (!string.IsNullOrEmpty(Request["id"]))
                    {
                        BindData(Request["id"]);
                        //将相关的公告设为已读
                        BLL.BulletinBLL.Instance.ReadBulletinByOrderID(Request["id"], Common.Enum.bulletinStatus.BeBuyer);
                    }
                    else
                    {
                        Response.Redirect("/Pages/ShoppingList.aspx");
                    }
                }
                else
                {
                    Response.Redirect(URL_INDEX);
                }
            }

            if (!string.IsNullOrEmpty(Request["hidStr"]))
            {
                ProcessRequest(Convert.ToBoolean(Request["hidStr"]));
            }
        }

        #region##处理请求
        /// <summary>
        /// 处理请求
        /// 创建人：Wilson
        /// 创建时间：2011-12-8
        /// </summary>
        /// <param name="isAgree"></param>
        private void ProcessRequest(bool isAgree)
        {
            string bulletinStr = string.Empty;

            if (isAgree)
            {
                AUV5.Model.OrderInfo order = AUV5.BLL.OrderInfoBLL.Instance.GetDetail(Request["id"]);

                order.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.Cloesd);

                AUV5.BLL.OrderInfoBLL.Instance.Update(order);

                bulletinStr = "买家{0}接受了你的取消订单请求";
            }
            else
            {
                AUV5.Model.OrderStatusLog statusLog = AUV5.BLL.OrderStatusLogBLL.GetInstance().GetOrderStatusLogByOrderId(Request["id"]);

                statusLog.LogContent = AUV5.BLL.OrderStatusLogBLL.GetInstance().GetNewLogContent(statusLog.LogContent, Convert.ToInt32(AUV5.Common.Enum.OrderState.BuyerRefusedToClosed));

                AUV5.BLL.OrderStatusLogBLL.GetInstance().Update(statusLog);

                bulletinStr = "买家{0}拒绝了你的取消订单请求";
            }

            AUV5.BLL.BulletinBLL.Instance.AddBulletin("订单提示", string.Format(bulletinStr, VerifiedInfo.User.UserName), Convert.ToString(ViewState["Seller"]), false, Convert.ToInt32(AUV5.Common.Enum.bulletinStatus.BeSeller), Request["id"]);

            BindData(Request["id"]);
        }
        #endregion

        #region##绑定数据
        /// <summary>
        /// 绑定数据
        /// 创建人：Wilson
        /// 创建时间：2011-12-7
        /// </summary>
        /// <param name="id"></param>
        private void BindData(string id)
        {
            AUV5.Model.OrderInfo order = AUV5.BLL.OrderInfoBLL.Instance.GetDetail(id);


            if (order != null)
            {
                ViewState["Seller"] = order.Seller;

                if (order.Buyer != base.VerifiedUserID)  //判断当前访问用户是否是该订单的买家
                {
                    Response.Redirect("/Pages/ShoppingList.aspx");
                }

                if (order.StatusID == Convert.ToInt32(AUV5.Common.Enum.OrderState.Default))
                {
                    Response.Redirect("/Pages/ShoppingList.aspx");
                }

                ShowDiv(order);    //显示、隐藏各操作层

                lblOrderCode.Text = order.OrderCode;   //订单号

                lblOrderBeginTime.Text = base.GetTimeSpan(order.BeginDate);  //订单开始时间

                AUV5.Model.UserInfo sellerUser = AUV5.BLL.UserInfoBLL.Instance.GetDetail(order.Seller);

                lblOrderStatus.Text = GetEnumDesc(typeof(AUV5.Common.Enum.OrderState), order.StatusID);

                if (sellerUser != null)
                {
                    imgSeller.ImageUrl = sellerUser.PhotoPath;            //卖家头像
                    lbtnContractSeller.Text = "联系 " + sellerUser.UserName;   //联系卖家

                }

                AUV5.Model.OrderItem item = AUV5.BLL.OrderItemBLL.Instance.GetOrderItemByOrderID(id);
                if (item != null)
                {
                    AUV5.Model.ServiceInfo service = AUV5.BLL.ServiceInfoBLL.Instance.GetDetail(item.ServiceID);
                    if (service != null)
                    {
                        lblServiceTitle.Text = service.Title;   //服务标题
                        lbtnContractSeller.PostBackUrl = "~/Pages/MessageShow.aspx?userID=" + sellerUser.UserID + "&serviceID=" + service.ServiceID;

                        ShowTip(order);   //显示信息
                    }
                }

                AUV5.Model.UserInfo buyerUser = AUV5.BLL.UserInfoBLL.Instance.GetDetail(order.Buyer);
                if (buyerUser != null)
                {
                    imgBuyer.ImageUrl = buyerUser.PhotoPath;
                }
            }
            else
            {
                Response.Redirect("/Pages/ShoppingList.aspx");
            }
        }
        #endregion

        #region##通过订单ID、订单状态显示层
        /// <summary>
        /// 通过订单ID、订单状态显示层
        /// 创建人：Wilson
        /// 创建时间：2011-12-5
        /// </summary>
        /// <param name="statusId"></param>
        private void ShowDiv(AUV5.Model.OrderInfo order)
        {
            AUV5.Model.OrderStatusLog statusLog = AUV5.BLL.OrderStatusLogBLL.GetInstance().GetOrderStatusLogByOrderId(order.OrderID);  //得到订单的状态改变记录

            bool isRequest = false;

            if (statusLog != null)
            {
                isRequest = AUV5.BLL.OrderStatusLogBLL.GetInstance().IsRequestClosed(statusLog.LogContent);

                lastIsRequest = Convert.ToString(isRequest);

                if (isRequest)   //如果最后一个状态是不是买/卖家请求取消订单
                {
                    IsShow(false, false, false, false);
                }
                else
                {
                    switch (order.StatusID)
                    {
                        case (int)AUV5.Common.Enum.OrderState.Payment:  //已付款提示
                            if (DateTime.Now >= order.EndDate) //如果超过时间未发货
                            {
                                IsShow(true, false, true, true);
                            }
                            else
                            {
                                IsShow(true, false, true, false);
                            }
                            break;
                        case (int)AUV5.Common.Enum.OrderState.Shipped:  //已发货提示
                            IsShow(true, true, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.Completed:   //已完成提示
                            IsShow(true, false, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.SysCompleted:   //系统自动完成订单提示
                            IsShow(true, false, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.HasEvaluation:   //买家已评价提示
                            IsShow(true, false, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.HasMutualEvaluation:   //双方互评提示
                            IsShow(false, false, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.Cloesd:                //交易关闭提示
                            IsShow(false, false, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.BuyerForceClosed:      //买家强制取消提示
                            IsShow(false, false, false, false);
                            break;
                        case (int)AUV5.Common.Enum.OrderState.SellerForceClosed:      //卖家强制取消提示
                            IsShow(false, false, false, false);
                            break;
                    }
                }
            }

        }

        /// <summary>
        /// 层的显示隐藏
        /// 创建人：Wilson
        /// 创建时间：2011-12-7
        /// </summary>
        /// <param name="sendOrder">发送消息操作</param>
        /// <param name="completeOrder">完成订单操作</param>
        /// <param name="cancelOrder">取消订单操作</param>
        /// /// <param name="cancelOrder">强制取消订单操作</param>
        private void IsShow(bool sendOrder, bool completeOrder, bool cancelOrder, bool forceCloesd)
        {
            btnCompleteOrder.Visible = completeOrder;   //完成订单
            divCompleteOrder.Visible = completeOrder;

            btnSendOrderLog.Visible = sendOrder;   //发送聊天
            divSendOrderLog.Visible = sendOrder;

            btnCancelOrder.Visible = cancelOrder;   //取消订单
            divCancelOrder.Visible = cancelOrder;

            divForceClosed.Visible = forceCloesd;

            if (sendOrder == false && completeOrder == false && cancelOrder == false)
            {
                imgBuyer.Visible = false;
            }
            else
            {
                imgBuyer.Visible = true;
            }
        }
        #endregion

        #region##通过订单号显示系统提示、订单状态改变提示、买卖对话
        /// <summary>
        /// 通过订单号显示系统提示、订单状态改变提示、买卖对话
        /// 创建人：Wilson
        /// 创建时间：2011-12-2
        /// </summary>
        /// <param name="orderCode"></param>
        private void ShowTip(AUV5.Model.OrderInfo order)
        {

            GetSystemTip(order);  //系统提示

            GetOrderStatusLog(order);   //订单状态提示

            GetEvaluation(order);   //得到评价

            GetMessage(order);        //订单买卖双方对话

        }
        #endregion

        #region##得到评价
        /// <summary>
        /// 得到评价
        /// 创建人：Wilson
        /// 创建时间：2011-12-20       
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        private void GetEvaluation(AUV5.Model.OrderInfo order)
        {
            AUV5.Model.FeedBack fb = AUV5.BLL.FeedBackBLL.Instance.GetFeedBackByOrderId(order.OrderID);

            if (fb != null)
            {
                messagelist.Add(new Evaluation(fb));
            }
        }
        #endregion

        #region##得到系统提示
        /// <summary>
        /// 显示系统提示
        /// 创建人：Wilosn
        /// 创建时间：2011-12-6
        /// </summary>
        /// <param name="order"></param>
        private void GetSystemTip(AUV5.Model.OrderInfo order)
        {
            DateTime lastHoursTime = order.EndDate.AddDays(-1);  //订单最后24小时
            //发货截止期提示     
            messagelist.Add(new SystemTip(SystemTip.TipType.Success, string.Format(OrderHelper.Buyer_OrderEndTimeTip, order.EndDate), order.BeginDate));

            if (DateTime.Now > lastHoursTime && order.StatusID < Convert.ToInt32(AUV5.Common.Enum.OrderState.Shipped))   //最近24小时提示
            {
                messagelist.Add(new SystemTip(SystemTip.TipType.Warning, OrderHelper.Buyer_LastHoursTip, lastHoursTime));
            }

            if (DateTime.Now >= order.EndDate && order.StatusID < Convert.ToInt32(AUV5.Common.Enum.OrderState.Shipped))   //到期提示
            {
                messagelist.Add(new SystemTip(SystemTip.TipType.Warning, OrderHelper.Buyer_EndDateTip, order.EndDate));
            }
        }
        #endregion

        #region##得到订单状态改变日志
        /// <summary>
        /// 显示订单状态改变日志
        /// 创建人：Wilson
        /// 创建时间：2011-12-6
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        private void GetOrderStatusLog(AUV5.Model.OrderInfo order)
        {
            List<AUV5.Model.ReadOrderStatusLog> readOrderStateList = AUV5.BLL.OrderStatusLogBLL.GetInstance().GetListReadOrderStatus(order.OrderID);
            string tips = "";
            foreach (AUV5.Model.ReadOrderStatusLog readOrderStateLog in readOrderStateList)
            {
                switch (readOrderStateLog.StatusId)
                {
                    case (int)AUV5.Common.Enum.OrderState.Default:   //未付款提示
                        tips = OrderHelper.OrderStatus_Default;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.Payment:  //已付款提示
                        tips = OrderHelper.OrderStatus_Payment;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.Shipped:  //已发货提示
                        tips = OrderHelper.OrderStatus_Shipped;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.Completed:   //已完成提示
                        tips = OrderHelper.OrderStatus_Completed;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.HasEvaluation:   //买家已评价提示
                        tips = OrderHelper.OrderStatus_HasEvaluation;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.HasMutualEvaluation:   //双方互评提示
                        tips = OrderHelper.OrderStatus_HasMutualEvaluation;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.BuyerRequestClosed:    //买家请求取消提示
                        if (base.VerifiedUserID == order.Buyer)
                        {
                            tips = AUV5.Common.OrderHelper.OrderStatus_BuyerRequestClosed2;
                        }
                        else
                        {
                            tips = AUV5.Common.OrderHelper.OrderStatus_BuyerRequestClosed;
                        }
                        break;
                    case (int)AUV5.Common.Enum.OrderState.SellerRequestClosed:    //卖家请求取消提示
                        tips = AUV5.Common.OrderHelper.OrderStatus_SellerRequestClosed;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.BuyerRefusedToClosed:     //买家拒绝取消提示
                        tips = OrderHelper.OrderStatus_BuyerRefusedToClosed;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.SellerRefusedToCloesd:   //卖家拒绝取消提示
                        tips = OrderHelper.OrderStatus_SellerRefusedToCloesd;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.Cloesd:                //交易关闭提示
                        tips = OrderHelper.OrderStatus_Cloesd;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.BuyerForceClosed:      //买家强制取消提示
                        tips = OrderHelper.OrderStatus_BuyerForceClosed;
                        break;
                    case (int)AUV5.Common.Enum.OrderState.SellerForceClosed:      //卖家强制取消提示
                        tips = OrderHelper.OrderStatus_SellerForceClosed;
                        break;
                }
                messagelist.Add(new SystemTip(SystemTip.TipType.Warning, tips, readOrderStateLog.CreateTime));
            }
        }
        #endregion

        #region##得到买卖双方留言
        /// <summary>
        /// 得到买卖双方留言
        /// 创建人：Wilson
        /// 创建时间：2011-12-6
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        private void GetMessage(AUV5.Model.OrderInfo order)
        {
            IList<AUV5.Model.OrderLog> list = AUV5.BLL.OrderLogBLL.GetInstance().GetListByOrderId(order.OrderID);

            foreach (AUV5.Model.OrderLog log in list)
            {
                AUV5.Model.UserInfo user = AUV5.BLL.UserInfoBLL.Instance.GetDetail(log.Sender);
                messagelist.Add(new Dialog(base.VerifiedUserID == log.Sender, user.PhotoPath, log.LogContent, log.CreateDate));
            }
        }
        #endregion

        #region##发送订单聊天消息
        /// <summary>
        /// 发送订单聊天消息
        /// 创建人：Wilson
        /// 创建时间：2011-12-5
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgBtnSendOrderLog_Click(object sender, ImageClickEventArgs e)
        {
            if (txtOrderLog.Text.Trim() == "")
            {
                base.Alert("请输入留言内容");
            }
            else
            {
                if (txtOrderLog.Text.Trim().Length > 500)
                {
                    base.Alert("留言内容不得大于500字");
                }
                else
                {
                    AUV5.Model.OrderInfo order = AUV5.BLL.OrderInfoBLL.Instance.GetDetail(Request["id"]);

                    if (order != null)
                    {
                        AUV5.Model.OrderLog orderLog = new Model.OrderLog();
                        orderLog.HistoryId = Guid.NewGuid().ToString();
                        orderLog.LogContent = txtOrderLog.Text.Trim();
                        orderLog.OrderID = order.OrderID;
                        orderLog.Receiver = order.Seller;
                        orderLog.Sender = base.VerifiedUserID;

                        AUV5.BLL.OrderLogBLL.GetInstance().Add(orderLog);

                        Response.Redirect("/Pages/ShoppingDetail.aspx?id=" + order.OrderID);

                        //BindData(Request["id"]);

                        //txtOrderLog.Text = "";
                    }
                }
            }
        }
        #endregion

        #region##收货按钮
        /// <summary>
        /// 收货按钮
        /// 创建人：Wilson
        /// 创建时间：2011-12-5
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgBtnCompleted_Click(object sender, ImageClickEventArgs e)
        {

            if (txtOrderLogCompleted.Text.Trim() == "")
            {
                base.Alert("留言内容不能为空");
            }
            else if (rdoBtnListRate.SelectedIndex == -1)
            {
                base.Alert("请选择好评或差评");
            }
            else
            {
                if (txtOrderLogCompleted.Text.Trim().Length > 500)
                {
                    base.Alert("最多不能超过500字");
                }
                else
                {

                    AUV5.Model.OrderInfo order = AUV5.BLL.OrderInfoBLL.Instance.GetDetail(Request["id"]);

                    if (order != null)
                    {
                        #region##
                        //AUV5.Model.OrderLog orderLog = new Model.OrderLog();
                        //orderLog.HistoryId = Guid.NewGuid().ToString();
                        //orderLog.LogContent = txtOrderLogCompleted.Text.Trim();
                        //orderLog.OrderID = order.OrderID;
                        //orderLog.Receiver = order.Buyer;
                        //orderLog.Sender = base.VerifiedUserID;
                        //AUV5.BLL.OrderLogBLL.GetInstance().Add(orderLog);
                        #endregion

                        AUV5.Model.FeedBack fb = new Model.FeedBack();
                        fb.Content = txtOrderLogCompleted.Text.Trim();
                        fb.FeedBackID = Guid.NewGuid().ToString();

                        AUV5.Model.OrderItem item = AUV5.BLL.OrderItemBLL.Instance.GetOrderItemByOrderID(order.OrderID);

                        if (rdoBtnListRate.SelectedValue == "0")
                        {
                            fb.IsGood = false;
                        }
                        else
                        {
                            fb.IsGood = true;
                        }

                        if (item != null)
                        {
                            fb.ServiceID = item.ServiceID;
                        }

                        fb.UserId = base.VerifiedUserID;
                        fb.OrderID = order.OrderID;

                        AUV5.BLL.FeedBackBLL.Instance.Add(fb);  //添加留言

                        order.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.Completed);

                        AUV5.BLL.OrderInfoBLL.Instance.Update(order);  //更新为订单已完成

                        order.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.HasEvaluation);

                        AUV5.BLL.OrderInfoBLL.Instance.Update(order);   //更新为已评价

                        AUV5.BLL.BulletinBLL.Instance.AddBulletin("订单提示", string.Format("买家{0}评价了你的服务", VerifiedInfo.User.UserName), Convert.ToString(ViewState["Seller"]), false, Convert.ToInt32(AUV5.Common.Enum.bulletinStatus.BeSeller), Request["id"]);

                        //BindData(Request["id"]);

                        //txtOrderLogCompleted.Text = "";

                        Response.Redirect("/Pages/ShoppingDetail.aspx?id=" + order.OrderID);
                    }
                }
            }
        }
        #endregion

        #region##取消按钮
        /// <summary>
        /// 取消按钮
        /// 创建人：Wilson
        /// 创建时间：2011-12-5
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgCancelOrder_Click(object sender, ImageClickEventArgs e)
        {
            if (txtOrderLogCancel.Text.Trim() == "")
            {
                base.Alert("留言不能为空");
            }
            else
            {
                if (txtOrderLogCancel.Text.Trim().Length > 500)
                {
                    base.Alert("不能大于500字");
                }
                else
                {
                    AUV5.Model.OrderInfo order = AUV5.BLL.OrderInfoBLL.Instance.GetDetail(Request["id"]);

                    if (order != null)
                    {
                        AUV5.Model.OrderLog orderLog = new Model.OrderLog();
                        orderLog.HistoryId = Guid.NewGuid().ToString();
                        orderLog.LogContent = txtOrderLogCancel.Text.Trim();
                        orderLog.OrderID = order.OrderID;
                        orderLog.Receiver = order.Seller;
                        orderLog.Sender = base.VerifiedUserID;
                        AUV5.BLL.OrderLogBLL.GetInstance().Add(orderLog);

                        AUV5.Model.OrderStatusLog statusLog = AUV5.BLL.OrderStatusLogBLL.GetInstance().GetOrderStatusLogByOrderId(order.OrderID);

                        string bulletinStr = string.Empty;

                        if (rdoBtnRequestClosed.Checked)
                        {
                            //更新订单状态日志                            
                            statusLog.LogContent = AUV5.BLL.OrderStatusLogBLL.GetInstance().GetNewLogContent(statusLog.LogContent, Convert.ToInt32(AUV5.Common.Enum.OrderState.BuyerRequestClosed));
                            AUV5.BLL.OrderStatusLogBLL.GetInstance().Update(statusLog);

                            bulletinStr = "买家{0}请求取消订单";
                        }
                        else if (rdoBtnForceClosed.Checked)
                        {
                            //更新订单
                            order.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.BuyerForceClosed);
                            AUV5.BLL.OrderInfoBLL.Instance.Update(order);

                            bulletinStr = "买家{0}强制取消订单";
                        }

                        AUV5.BLL.BulletinBLL.Instance.AddBulletin("订单提示", string.Format(bulletinStr, VerifiedInfo.User.UserName), Convert.ToString(ViewState["Seller"]), false, Convert.ToInt32(AUV5.Common.Enum.bulletinStatus.BeSeller), Request["id"]);

                        //BindData(Request["id"]);

                        Response.Redirect("/Pages/ShoppingDetail.aspx?id=" + order.OrderID);
                    }
                }
            }

        }
        #endregion
    }
}